package org.csu.mypetstore.web.servlets;

//import net.sf.json.JSONArray;
//import net.sf.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.csu.mypetstore.domain.Product;
import org.csu.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;


public class HandleSearchServlet extends HttpServlet {
    private String keyword;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取搜索框中的关键词
        keyword = request.getParameter("keyword");
        CatalogService service = new CatalogService();

        //获得搜索的产品列表
        List<Product> productList = service.searchProductList(keyword);
        response.setContentType("application/json;charset=utf-8");
        JSONArray searchArray = new JSONArray();
        for(int i = 0 ; i < productList.size() ; i++){
            JSONObject searchObject = new JSONObject();
            //产品名称
            searchObject.put("name",productList.get(i).getName());
            //产品图片
            int firstIndexOfImg = productList.get(i).getDescription().indexOf('=');
            int lastIndexOfImg = productList.get(i).getDescription().indexOf('>');
            String imgString = productList.get(i).getDescription().substring(firstIndexOfImg+1,lastIndexOfImg);
            System.out.println(imgString);
            searchObject.put("description",imgString);
            //添加得到数组中
            searchArray.add(searchObject);
        }
        //转换成JSON字符串
        String searchString = searchArray.toJSONString();
        System.out.println(searchString);
        PrintWriter out = response.getWriter();
        out.print(searchString);
    }
}
